package com.gyhy.dumplings.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gyhy.dumplings.auth.feign.CustomerFeignService;
import com.gyhy.dumplings.common.utils.HttpUtils;
import com.gyhy.dumplings.common.utils.JwtUtils;
import com.gyhy.dumplings.common.utils.R;
import com.gyhy.dumplings.common.vo.MemberResponseVo;
import com.gyhy.dumplings.common.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @author 光影灰翼
 * @Description: 处理社交登录请求
 **/

@Slf4j
@Controller
@RefreshScope
// @RestController
@RequestMapping("/oauth")
public class OAuth2Controller {

    @Autowired(required = false)
    private CustomerFeignService customerFeignService;

    @Value("${gitee.client_id:3f86a28a47d940609802c9c099c2cb54b5e6039a4aeda4d9f409b755f6d3d617}")
    private String client_id;
    @Value("${gitee.client_secret:d2db019c3dab5131a8138ac64db914b89b10f540b9895395c7c5e03bf4b88a6f}")
    private String client_secret;
    @Autowired
    private RedisTemplate redisTemplate;




    @GetMapping(value = "/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {


        Map<String, String> map = new HashMap<>();
        map.put("client_id",client_id);
        map.put("client_secret",client_secret);
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://127.0.0.1:8840/api/oauth/oauth2.0/gitee/success");
        map.put("code",code);

        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com","/oauth/token","post",new HashMap<String,String>(),map,new HashMap<String,String>());
        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取access_token
            String json = EntityUtils.toString(response.getEntity());
            HashMap tokenMap = JSON.parseObject(json, HashMap.class);
            String token= (String) tokenMap.get("access_token");
            System.out.println(token);
            //通过token获取userInfo
            HttpResponse response2 = HttpUtils.doGet("https://gitee.com","/api/v5/user?access_token="+token,"get",new HashMap<String,String>(),new HashMap<String,String>());
            String json2 = EntityUtils.toString(response2.getEntity());
            System.out.println(json2);
            HashMap tokenMap2 = JSON.parseObject(json2, HashMap.class);
            //将信息填入socialUser中
            SocialUser socialUser = new SocialUser((Integer) tokenMap2.get("id"), (String) tokenMap2.get("name"));
            System.out.println(socialUser);

            //知道了哪个社交用户
            //1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R oauthLogin = customerFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {});
                String info=JSON.toJSONString(data);
                log.info("登录成功：用户信息：{}",info);

                //将信息存入token中;
                String key = String.valueOf(UUID.randomUUID());
                if(redisTemplate.opsForValue().get(key) == null) {
                    //将登陆的信息保存如redis
                    redisTemplate.opsForValue().set(key, info);
                }
                //设置token有效的时间
                redisTemplate.expire(key, 1, TimeUnit.DAYS);
                String userToken = JwtUtils.getJwtToken(key);
                System.out.println("uuid:"+key);
                System.out.println("decode:"+JwtUtils.decode(userToken));

                //2、登录成功跳回首页,返回token
                return "redirect:http://localhost:5173/loginGiteeSuccess?info="+userToken;
            } else {
                return "redirect:http://localhost:5173/giteeLogin?login=false";
            }
        } else {
            return "redirect:http://localhost:5173/giteeLogin?login=false";
        }

    }

}
